package leetcodev1.字符串;

import leetcodev1.链表.Solution;

public class LeetCode28 {

    //KMP字符串匹配
    //关键在于前缀函数-定义重复元素个数
    public int strStr(String haystack, String needle) {
        int n = haystack.length(), m = needle.length();
        if (m == 0) {
            return 0;
        }
        int[] pi = new int[m];
        for (int i = 1, j = 0; i < m; i++) {
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
                j = pi[j - 1];
            }
            if (needle.charAt(i) == needle.charAt(j)) {
                j++;
            }
            pi[i] = j;
        }
        for (int i = 0, j = 0; i < n; i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = pi[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
            }
            if (j == m) {
                return i - m + 1;
            }
        }
        return -1;
    }

    //匹配子串
    //暴力解法 每个起点都试试
    public int strStr1(String haystack, String needle) {
        if (needle.length() > haystack.length()) {
            return -1;
        }
        int haystackLength = haystack.length();
        int needleLength = needle.length();
        for (int i = 0; i < haystackLength; i++) {
            if (compare(haystack, needle, i, haystackLength, needleLength)) {
                return i;
            }
        }
        return -1;
    }

    private boolean compare(String haystack, String needle, int haystackIndex, int haystackLength, int needleLength) {
        if (haystackIndex + needleLength > haystackLength) {
            return false;
        }

        int index = 0;
        while (index < needleLength) {
            if (needle.charAt(index) != haystack.charAt(haystackIndex + index)) {
                return false;
            }
            index++;
        }
        return true;
    }
}
